// tslint:disable
import { Component, OnInit, Input, OnDestroy } from "@angular/core";
import { ActionSheetController, AlertController } from "@ionic/angular";
import { ModalController } from "@ionic/angular";
import { Subscription } from "rxjs";
import { MessageService } from "src/app/shared/service/message.service";
import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';
import { EventService } from 'src/app/shared/service/event.service';
import { Platform } from '@ionic/angular';
import { AppGlobalService } from "../../shared/service/app-global.service";
import { HttpService } from "../../shared/service/http.service";
import { ShareService } from 'src/app/shared/service/share.service';
import { ImgSlidePage } from "../slides-imgage/img-slide.page";
import { PageModalService } from "src/app/shared/service/page-modal-service";
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';

@Component({
  selector: 'app-shop-address-list',
  templateUrl: './shop-address-list.component.html',
  styleUrls: ['./shop-address-list.component.scss'],
})
export class ShopAddressListComponent implements OnInit {

  @Input() tagData: any;
  formGroup: FormGroup = new FormGroup({});
  openInformation = false;
  openRemarks = false;
  icons = [];
  remarksText = "";
  remarksIcon: any;
  phoneArray = [];
  dataIndex: any;
  firstTextStyle: any = {};
  secondTagStyle: any = {};
  firstTagStyle: any = {};
  secondTestStyle: any = {};
  pageNo: any = 1;
  params: any = { content: {} };
  currentIndex = -1;
  sessionId = localStorage.getItem("sessionId");
  // 声明订阅对象
  subscription: Subscription = null;
  emptyDataHint = "暂无数据";
  showLoadMore = false;
  pageSize: number;
  pageTotal: number;
  finalProfit: any;
  orderAmount: any;
  cost: any;
  discountAmount: any;
  customerMobile: any;
  currentProfit: any;

  constructor(
    private appGlobalService: AppGlobalService,
    private actionSheetCtrl: ActionSheetController,
    private actionSheet: ActionSheetService, // 必须有
    private alertController: AlertController,
    private eventService: EventService,
    private message: MessageService,
    private platform: Platform,
    private httpService: HttpService,
    private iab: InAppBrowser,
    private shareService: ShareService,
    private pageModalService: PageModalService,
    public modalController: ModalController) {



    this.eventService.eventEmit.on("openPageModalWithParams", (obj) => {
      if (obj) {
        this.openPageModalWithParams(obj);
      }
    });

    // 监听多选后
    if (this.eventService.eventEmit.listenerCount('auditNow') > 0) {
      this.eventService.eventEmit.removeListener('auditNow');
    }
    this.eventService.eventEmit.on('auditNow', obj => {
      // console.log(res);
      if (obj.target) {
        this.openPageModalWithParams(obj);
      } else {
        // submit
      }
    });
  }




  openPageModalWithParams(obj) {
    const that = this;
    try {
      if (obj && (obj.type === 'modal' || obj.type == 'pageModal' || obj.type == 'model')) {
        if (obj.params) {
          if (that.discountAmount) {
            obj.params['discount_price'] = that.discountAmount;
          } else {
            obj.params['discount_price'] = 0;
          }
          const pattern = new RegExp('^1(3|4|5|6|7|8|9)\\d{9}$');
          if (!that.customerMobile) {
            this.appGlobalService.showToast("请填写客户手机", 2000, "middle");
            return;
          } else if (that.customerMobile && that.customerMobile.length !== 11) {
            this.appGlobalService.showToast("手机号应为11位数", 2000, "middle");
            return;
          } else if (that.customerMobile && !that.customerMobile.match(pattern)) {
            this.appGlobalService.showToast("请填入正确的手机号", 2000, "middle");
            return;
          } else {
            obj.params['customer_mobile'] = that.customerMobile;
          }
          this.pageModalService.openPage(obj);
        } else {
          return;
        }
      }
    } catch (error) {

    }
  }

  ngOnInit() {
    const listenerName = this.tagData.name + 'AskForList';
    console.log('msg----->' + listenerName);
    console.log('tagData', this.tagData);
    this.eventService.eventEmit.on(listenerName, (obj) => {
      this.refreshListData(obj);
    });
    // this.createControl();
    this.params = this.tagData.data.submit;
    if (this.tagData && this.tagData.hint) {
      this.emptyDataHint = this.tagData.hint;
    }
  }
  showModal(link) {
    const that = this;
    this.pageModalService.openPage(link, '', result => {
      if (result) {
        // that.updateItem();
      }
    });

  }
  createControl() {
    let that = this;
    that.tagData.data.footDiv.details.forEach(element => {
      if (element.formKey) {
        that.formGroup.addControl(element.formKey, new FormControl('', []));
      }
    });
  }
  refreshListData(param) {
    const that = this;
    if (param === undefined) {
      return;
    }
    this.pageNo = 1;
    if (!param.showName) {
      if (this.tagData.data.submit && this.tagData.data.submit.content) {
        param.showName = this.tagData.data.submit.content.showName;
      }
    }
    this.params.content = param;
    this.params.id = this.tagData.data.submit.id;
    this.params.content.pageNo = this.pageNo;
    this.params.sessionId = localStorage.getItem("sessionId");
    this.httpService.post('application/submit', this.params, res => {
      if (res.success) {
        if (res.data.submit) {
          this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }
        this.tagData.data.data = [];
        const result = res.data.data; // JSON.parse(res.data.data);
        this.tagData.data.data = result;
        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        this.pageTotal = this.tagData.pageTotal;
        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }

  /**
   *
   * @param item 打开图标
   */
  openIcon(item, dataIndex?, maxIconList?) {
    if (maxIconList && maxIconList === '2') {
      this.icons = item.slice(1);
    } else {
      this.icons = item.slice(2);
    }

    this.showActionSheet(this.icons);
    // this.openInformation = true;
    this.dataIndex = dataIndex;
  }

  /**
   * 关闭图标
   */
  hiddenInformation() {
    this.openInformation = false;
    this.openRemarks = false;
  }

  /**
   *
   * @param item 点击图标
   */
  iconClick(item) {
    const that = this;
    if (item.link) {
      if (item.link.type === 'page') {
        const params = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(params);
      } else if (item.link.type === 'model') {
        item.link.modalCss = 'auto-modal';
        this.pageModalService.openPage(item.link, '', result => {
          if (result) {
          }
        });

      }
    }
    if (item.button) {

      if (item.action && item.action === 'question') {
        // this.presentAlertWithMsgBtn(item.label, item.text ? item.text : '确定', item.button);
      } else {

        if (item.button.submit) {
        }
      }
    }
    if (item.modelType === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//
        this.httpService.gotoChat(item);
      } else if (item.label === '分享') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
        });
      } else {
        // 修改
        const params = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(params);
      }
    }
    if (item.modelType === "iconSubmit") {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (item.link && item.link.target) {
            const pageParams = {
              pageId: item.link.target,
              params: item.link.params ? item.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    }
    if (item.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
    if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      this.presentAlertConfirm(Number(this.phoneArray[0]), item.label);

    }
    if (item.modelType === "dialog") {

    }
    if (item.modelType === 'pageDialog') {

    }
  }

  selectItem(item, index) {

  }
  showActionSheet(icons) {
    const that = this;
    const buttons: any = [];
    icons.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          ActionSheetService.close();
          that.iconClick(icons[buttonIndex]);
        }
      }
    );
  }

  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }
  go(item, e) {
    e.stopPropagation();
    // todo 与后台API沟通返回的link结构 不正确 item.link.type
    if (item.link && item.link.link && item.link.link.type === 'address') {
      const addressUrl = this.appGlobalService.baiduNavigationAPI + '?location=' + item.link.link.params.location
        + '&title=' + item.link.link.params.title + '&content=' + item.link.link.params.content + '&output=html';
        if (localStorage.getItem('platform') === 'ios') {
          const sch = 'baidumap://map/marker?location=' + item.link.link.params.location + '&title=' + item.link.link.params.title + '&content=' + item.link.link.params.content + '&src=ios.baidu.openAPIdemo&coord_type=gcj02';
          this.iab.create(sch, '_system');
        } else {
          window.open(addressUrl, '_system');
        }
      
    } else if (item.link && item.link.link && item.link.link.type === 'phone') {
      this.presentAlertConfirm(Number(item.link.link.params.mobile), item.link.link.params.userName);
    } else if (item.link && item.link.link && item.link.link.type === 'chat') {
      this.httpService.gotoChat({ link: { params: {} } }, item.link.link.params.userId);
    } else {
      if (item.link.link) {
        this.pageModalService.openPage(item.link.link);
      } else {
        this.pageModalService.openPage(item.link);
      }
    }
  }
  refreshData(event?) {
    this.params.sessionId = localStorage.getItem("sessionId");
    // 请求下一个页面
    this.pageNo = 1;
    this.params.content.pageNo = this.pageNo;
    // 请求获取新数据
    this.httpService.post("application/submit", this.params, res => {
      // 请求数据成功
      if (res.success) {

        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
          this.tagData.data.data = res.data.data;

          // this.params = res.data.submit;
        } else {
          this.tagData.data.data = [];
          // 没有数据了
          // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
        }
        if (event) {
          event.target.complete();
        }

      } else {
        // 请求失败，更新当前页数
        this.tagData.data.data = [];
        this.pageNo = 1;
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
        if (event) {
          event.target.complete();
        }
      }
    });
  }

  loadData(event) {
    setTimeout(() => {
      this.params.sessionId = localStorage.getItem("sessionId");
      // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.httpService.post("application/submit", this.params, res => {
        // 请求数据成功
        if (res.success) {
          // 追加返回数据
          if (Array.isArray(res.data.data) && res.data.data.length > 0) {
            // 追加数据
            res.data.data.map(item => {
              this.tagData.data.data.push(item);
            });
            // this.params = res.data.submit;
          } else {
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
          }
          event.target.complete();
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
          event.target.complete();
        }
      });
    }, 500);
  }

  async previewImage(imageUrl, tmpIndex, isPreview) {
    // event.stopPropagation();
    if (isPreview && isPreview !== undefined) {
      // const that = this;
      let tempImageUrl = 'assets/img/default_img.png';
      if (imageUrl !== undefined) {
        tempImageUrl = imageUrl;
      }
      const value = { img: [tempImageUrl], index: tmpIndex };
      const modal = await this.modalController.create({
        component: ImgSlidePage,
        componentProps: { value: JSON.stringify(value) }
      });
      return await modal.present();
    }

  }
  call(phone, name) {
    event.stopPropagation();
    this.presentAlertConfirm(Number(phone), name);
  }
  ngOnDestroy(): void {
    this.eventService.removeCustomListListeners();
  }

  copyUrl(str) {
    this.appGlobalService.copyString(str);
  }

  // 评分
  updateRateReturn(event, item, dateIndex) {
    if (item) {

    }
    // item.data.forEach(element => {
    //   if (element.value === event) {
    //     item.showValue = element.label;
    //   }
    // });    
  }

  changeValue(event, item) {
    // console.log('item', item);
    // console.log('value', event.detail.value);
    if (item.textType === 'Number') {
      // item.value = event.detail.value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')
    }
    if (event.detail.value.length > Number(item.maxLength)) {
      item.value = event.detail.value.slice(0, Number(item.maxLength));
      this.formGroup.patchValue({ [item.formKey]: item.value });
    }
    // 1.最终利润 = 订单金额 - 成本 - 优惠金额。
    // 2.实收 =  订单金额 -  优惠金额。
    if (item.formKey === 'discount_price') {
      this.discountAmount = event.detail.value;
      const orderTemp = Number(this.orderAmount).toFixed(2);
      this.finalProfit = Number(orderTemp) - event.detail.value - this.cost;
      let saleTotalPrice = Number(orderTemp) - event.detail.value;
      if (saleTotalPrice < 0) {
        saleTotalPrice = 0;
      }
      if (this.finalProfit < 0) {
        this.finalProfit = 0;
      }
      this.eventService.eventEmit.emit('Total', { saleTotal: saleTotalPrice });
    } else if (item.formKey === 'customer_mobile') {
      this.customerMobile = event.detail.value;
    }
  }



  getInterger(value) {
    return parseInt(value);
  }


}
